package com.xiaoxin.urlshorter.DataDictionary;


import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author jinbo.song
 * @description 解析XML文件
 */
public class XMLDDItemParser {

    private static Logger logger= LoggerFactory.getLogger(XMLDDItemParser.class);
    //获取字典项结构
    public static DataDictionaryItems dataItems ;

    private static String DICT_CODE = "code";

    private static String DICTITEM_NAME = "name";

    private static String DICTITEM_VALUE = "value";

    public XMLDDItemParser(){}


    /**
     * 根据分组编号来解析XML文件，获取该分组下数据字典项集
     * @param dicCode
     * @return DataDictionaryItem
     */
    public static List<DataDictionaryItem> parseXML(String dicCode){
        List<DataDictionaryItem> dictList=new ArrayList<>();
        try {
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(ResourceUtils.getFile("classpath:DataDictionaryConfig.xml"));
            List list =document.selectNodes("//dict");
            Iterator iterator = list.iterator();
            while(iterator.hasNext()){
                Node node=(Node)iterator.next();
                if(node instanceof Element){
                    Element element = (Element) node;
                    String dictCode=element.attributeValue(DICT_CODE);
                    //取组内数据字典项
                    if(dicCode.equals(dictCode)){
                        //根据数据字典项名称编码
                        Iterator elemIter=element.elementIterator();
                        while(elemIter.hasNext()){
                            DataDictionaryItem dataDictionaryItem = new DataDictionaryItem();
                            Element elem =(Element)elemIter.next();
                            dataDictionaryItem.setItemName(elem.attributeValue(DICTITEM_NAME));
                            dataDictionaryItem.setItemValue(elem.attributeValue(DICTITEM_VALUE));
                            dictList.add(dataDictionaryItem);
                        }
                    }
                }
            }

        } catch (Exception ex) {
            if(logger.isDebugEnabled()){
                logger.debug(ex.getMessage());
            }
        }
        return dictList;
    }

}
